/*
 * Copyright (c) 2014 - 2017. Company.Domain Co.Ltd. All rights reserved.
 */

package cn.com.dhc.danlu.activity.terminal;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.com.dhc.danlu.R;
import cn.com.dhc.danlu.activity.BaseActivity;
import cn.com.dhc.danlu.activity.LoginActivity;
import cn.com.dhc.danlu.dlware.OperatorUtils;
import cn.com.dhc.danlu.dlware.net.GeneralBusinessObserver;
import cn.com.dhc.danlu.util.CommonUtils;
import cn.com.dhc.danlu.util.ToastUtil;
import cn.com.dhc.danlu.widget.dialog.ViewDialog;
import cn.com.dhc.danlu.widget.loadlayer.LoaddingLayout;
import cn.com.dhc.danlu.widget.terminal.TimeView;
import cn.com.hd.mall.web.webservices.entity.request.login.LoginRequest;
import cn.com.hd.mall.web.webservices.entity.request.regist.TerminalRequest;
import cn.com.hd.mall.web.webservices.entity.response.regist.TerminalRegistProgressResponse;
import cn.com.hd.mall.web.webservices.entity.response.regist.TerminalRegistProgressResponse.RegistProgressBean;

import static cn.com.dhc.danlu.dlware.global.DanluApplication.agent;

/**
 * author: 李一方(<a href="mailto:liyifang@danlu.com">liyifang@danlu.com</a>)<br/>
 * author: 刘立琦(<a href="mailto:liuliqi@danlu.com">liuliqi@danlu.com</a>)<br/>
 * version: 1.0.0<br/>
 * since: 2016-08-29 15:06<br/>
 * <p>
 * <p>
 * 审批进度界面
 * </p>
 */
public class TerminalProgressActivity extends BaseActivity implements View.OnClickListener {
    private static final int RECORD_SIZE = 4;
    private ImageView ivBack;
    private TextView tvPhone;
    private TextView tvAccount;
    private TextView tvShopName;
    private TextView tvBusinessLicense;
    private TextView tvShopType;
    private TextView tvShopAddress;
    private TextView tvShopDetail;
    private TextView tvInvitation;
    private TextView tvCall;
    private Button btnResubmit;
    private ImageView ivMore;
    private RelativeLayout rlMore;
    private LinearLayout llContent;

    private boolean isExpand;
    private LoginRequest form;
    private Map<String, String> shopType;
    private TerminalRegistProgressResponse result;

    private LoaddingLayout llLoading;

    private List<RegistProgressBean> datas;

    @Override
    protected void onCreate (Bundle savedInstanceState) {
        super.onCreate (savedInstanceState);
        setContentView (R.layout.activity_terminal_progress);

        initArgs ();
        initViews ();
        setupView ();
    }

    @Override
    protected String getActivityTitle () {
        return null;
    }

    private void refreshInfo (TerminalRegistProgressResponse result) {
        tvPhone.setText (result.getRegistInfo ().getTerminalTel ());
        tvAccount.setText (result.getRegistInfo ().getTerminalUserName ());
        tvShopName.setText (result.getRegistInfo ().getTerminalName ());
        tvBusinessLicense.setText (result.getRegistInfo ().getBusinessLicenseCode ());
        tvShopType.setText (shopType.get (result.getRegistInfo ().getTerminalTypeCode ()));
        tvShopAddress.setText (result.getRegistInfo ().getTerminalAreaFullName ());
        tvShopDetail.setText (result.getRegistInfo ().getTerminalDetailAddress ());
        tvInvitation.setText (result.getRegistInfo ().getInvitationCode ());
        btnResubmit.setVisibility (result.getStatus ().equals ("1") ? View.VISIBLE : View.GONE);
    }

    private void refreshList (List<RegistProgressBean> data) {
        if (null == data || data.size () == 0) {
            TimeView view = new TimeView (TerminalProgressActivity.this);
            view.setStatus ("暂无记录", null);
            view.setTime (CommonUtils.getDate (new Date (), "MM-dd hh:mm:ss"));
            view.setLineTopVisible (View.INVISIBLE);
            view.setLineBottomVisible (View.INVISIBLE);
            rlMore.setVisibility (View.GONE);
            rlMore.setVisibility (View.GONE);
            llContent.addView (view);
        } else {
            addView (data, data.size () <= RECORD_SIZE);
        }
    }

    private void addView (List<RegistProgressBean> data, boolean isFlag) {
        if (isFlag) {
            rlMore.setVisibility (View.GONE);
        } else {
            rlMore.setVisibility (View.VISIBLE);
        }

        for (int i = 0; i < (isFlag ? data.size () : RECORD_SIZE); i++) {
            TimeView view = new TimeView (TerminalProgressActivity.this);
            view.setData (data.get (i));
            if (i == 0) {
                view.setLineTopVisible (View.INVISIBLE);
            }

            if (i == (isFlag ? (data.size () - 1) : (RECORD_SIZE - 1))) {
                view.setLineBottomVisible (View.GONE);
            }

            llContent.addView (view);
        }
    }

    private void initArgs () {
        shopType = new HashMap<> ();
        shopType.put ("S011", "烟酒专卖店");
        shopType.put ("S012", "便利店");
        shopType.put ("S013", "餐饮店");
        shopType.put ("S014", "商业超市");
        shopType.put ("S015", "其他");

        String password = getIntent ().getStringExtra ("password");
        String loginname = getIntent ().getStringExtra ("loginname");
        if (!TextUtils.isEmpty (loginname) && !TextUtils.isEmpty (password)) {
            form = new LoginRequest ();
            form.setUsername (loginname);
            form.setPassword (password);
        } else {
            finish ();
        }

        getDatas ();
    }

    /**
     * 发起网络请求，获取数据
     */
    private void getDatas () {
        agent.getApi ()
                .registerProgress (form)
                .compose (OperatorUtils.<TerminalRegistProgressResponse>defaultSchedulers ())
                .subscribe (new GeneralBusinessObserver<TerminalRegistProgressResponse> () {
                    @Override
                    protected void onSuccess (TerminalRegistProgressResponse model) {
                        String status = model.getStatus ();
                        result = model;
                        refreshInfo (model);
                        datas = model.getRegistProgress ();
                        refreshList (datas);
                        llLoading.showContentView ();
                        // 审核中提示已经在登陆界面中弹出
                        if (status.equals ("1")) {
                            ToastUtil.getInstance ().show ("审批被拒绝");
                        }
                    }

                    @Override
                    protected void onAlertTips (String displayMessage) {
                        llLoading.showErrorView (TextUtils.isEmpty (displayMessage) ? "获取审批进度失败" : displayMessage);
                    }
                });
    }

    private void initViews () {
        ivBack = (ImageView) findViewById (R.id.iv_back);
        tvPhone = (TextView) findViewById (R.id.tv_phone);
        tvAccount = (TextView) findViewById (R.id.tv_account);
        tvShopName = (TextView) findViewById (R.id.tv_shop_name);
        tvBusinessLicense = (TextView) findViewById (R.id.tv_business_license);
        tvShopType = (TextView) findViewById (R.id.tv_shop_type);
        tvShopAddress = (TextView) findViewById (R.id.tv_shop_address);
        tvShopDetail = (TextView) findViewById (R.id.tv_shop_detail);
        tvInvitation = (TextView) findViewById (R.id.tv_invitation);
        tvCall = (TextView) findViewById (R.id.tv_call);
        btnResubmit = (Button) findViewById (R.id.btn_resubmit);
        ivMore = (ImageView) findViewById (R.id.iv_more);
        rlMore = (RelativeLayout) findViewById (R.id.rl_more);
        llContent = (LinearLayout) findViewById (R.id.ll_content);
        llLoading = (LoaddingLayout) findViewById (R.id.ll_loading);
    }

    private void setupView () {
        tvCall.setOnClickListener (this);
        ivBack.setOnClickListener (this);
        rlMore.setOnClickListener (this);
        btnResubmit.setOnClickListener (this);

        llLoading.setErrorViewRetryClickListener (new View.OnClickListener () {
            @Override
            public void onClick (View v) {
                llLoading.showLoaddingView ();
                // add by llq
                getDatas ();
            }
        });
    }

    @Override
    public void onBackPressed () {
        toPrevious ();
    }

    @Override
    public void onClick (View v) {
        switch (v.getId ()) {
            case R.id.iv_back:
                toPrevious ();
                break;

            case R.id.btn_resubmit:
                TerminalRequest request = new TerminalRequest ();
                request.setApplyId (result.getRegistInfo ().getApplyId ());
                request.setTerminalName (result.getRegistInfo ().getTerminalName ());
                request.setTerminalTypeCode (result.getRegistInfo ().getTerminalTypeCode ());
                request.setTerminalAreaCode (result.getRegistInfo ().getTerminalAreaCode ());
                request.setBusinessLicenseCode (result.getRegistInfo ().getBusinessLicenseCode ());
                request.setTerminalDetailAddress (result.getRegistInfo ().getTerminalDetailAddress ());

                Intent intent = new Intent (TerminalProgressActivity.this, ModifyTerminalInfoActivity.class);
                intent.putExtra ("data", request);
                intent.putExtra ("username", result.getRegistInfo ().getTerminalUserName ());
                intent.putExtra ("phone", result.getRegistInfo ().getTerminalTel ());
                intent.putExtra ("address", result.getRegistInfo ().getTerminalAreaFullName ());
                intent.putExtra ("shopTypeName", shopType.get (request.getTerminalTypeCode ()));
                intent.putExtra ("loginData", form);
                startActivity (intent);
                finish ();
                break;

            case R.id.tv_call:
                callHelp ();
                break;

            case R.id.rl_more:
                toggleAddView ();
                break;

            default:
                break;
        }
    }

    /**
     * 回到上一界面
     */
    private void toPrevious () {
        Intent intent;
        intent = new Intent (TerminalProgressActivity.this, LoginActivity.class);
        startActivity (intent);
        finish ();
    }

    private void toggleAddView () {
        if (!isExpand) {
            ((TimeView) llContent.getChildAt (RECORD_SIZE - 1)).setLineBottomVisible (View.VISIBLE);

            for (int i = (RECORD_SIZE + 1); i < datas.size (); i++) {
                TimeView view = new TimeView (TerminalProgressActivity.this);
                view.setData (datas.get (i));

                if (i == (datas.size () - 1)) {
                    view.setLineBottomVisible (View.GONE);
                }
                llContent.addView (view);
            }
            isExpand = true;
        } else {
            ((TimeView) llContent.getChildAt (RECORD_SIZE - 1)).setLineBottomVisible (View.GONE);
            llContent.removeViews (RECORD_SIZE, datas.size () - RECORD_SIZE - 1);
            isExpand = false;
        }

        ivMore.setSelected (isExpand);
    }

    /**
     * 呼叫客服
     */
    private void callHelp () {
        new ViewDialog.Builder (TerminalProgressActivity.this)
                .setTitle ("联系客服")
                .setMessage ("确定拨打400-011-6666")
                .setCancelable (false)
                .setNegativeButton (R.string.btn_cancel, new DialogInterface.OnClickListener () {
                    @Override
                    public void onClick (DialogInterface dialog, int which) {
                        dialog.dismiss ();
                    }
                })
                .setPositiveButton (R.string.btn_confirm, new DialogInterface.OnClickListener () {
                    @Override
                    public void onClick (DialogInterface dialog, int which) {
                        dialog.dismiss ();
                        CommonUtils.callHelp (TerminalProgressActivity.this);
                    }
                }).create ().show ();
    }
}